import { ref } from "vue";
import { ElNotification } from "element-plus";
import useUserStore from "@/store/modules/user";

class WebSocketService {
  constructor() {
    this.socket = null;
    this.reconnectAttempts = 0;
    this.maxReconnect = 5;
    this.baseUrl = import.meta.env.VITE_WS_URL;
    this.messageHandlers = new Set();
  }

  init() {
    const userStore = useUserStore();
    if (this.socket || !userStore.isAuthenticated) return;

    this.socket = new WebSocket(`${this.baseUrl}/ws/notifications/`);

    this.socket.onopen = () => {
      console.log("WebSocket  connected");
      this.reconnectAttempts = 0;
      this.heartbeat();
    };

    this.socket.onmessage = (e) => {
      try {
        const data = JSON.parse(e.data);
        this.messageHandlers.forEach((handler) => handler(data));
      } catch (err) {
        console.error("WebSocket  message parse error:", err);
      }
    };

    this.socket.onclose = () => {
      console.log("WebSocket  disconnected");
      this.handleReconnect();
    };

    this.socket.onerror = (err) => {
      console.error("WebSocket  error:", err);
    };
  }

  addMessageHandler(handler) {
    this.messageHandlers.add(handler);
  }

  removeMessageHandler(handler) {
    this.messageHandlers.delete(handler);
  }

  heartbeat() {
    if (!this.socket) return;
    this.heartbeatTimer = setInterval(() => {
      if (this.socket.readyState === WebSocket.OPEN) {
        this.socket.send(JSON.stringify({ type: "ping" }));
      }
    }, 30000);
  }

  handleReconnect() {
    if (this.reconnectAttempts >= this.maxReconnect) return;

    this.reconnectAttempts++;
    const delay = Math.min(1000 * this.reconnectAttempts, 10000);

    setTimeout(() => {
      console.log(`Reconnect  attempt ${this.reconnectAttempts}`);
      this.init();
    }, delay);
  }

  close() {
    if (this.socket) {
      clearInterval(this.heartbeatTimer);
      this.socket.close();
      this.socket = null;
    }
  }
}

// 单例模式导出
export const websocketService = new WebSocketService();
